package cn.edu.jxust.application.filter;

import cn.edu.jxust.core.infrastructure.util.authc.JwtToken;
import cn.edu.jxust.common.response.Result;
import cn.edu.jxust.common.response.ResultUtils;
import cn.edu.jxust.common.response.enums.ResultStatus;
import cn.edu.jxust.core.infrastructure.util.authc.JwtConst;
import cn.edu.jxust.core.infrastructure.util.authc.JwtUtils;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author QiuKangming
 * @version 1.0
 * @description jwt过滤器
 * @since 2020/06/28 12:59
 */

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * jwt 工具类
     */
    private final JwtUtils jwtUtils;

    /**
     * 构造方法
     * @param jwtUtils jwtUtils
     */
    public JwtFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    /**
     * 检查请求头中是否有 token 令牌
     * @param request ServletRequest
     * @return boolean
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {

        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(JwtConst.RESPONSE_HEADER);
        return authorization != null;

    }

    /**
     * 首先调用的方法, 返回请求是否被允许
     * @param request request
     * @param response response
     * @param mappedValue mappedValue
     * @return true: 允许访问, false: 非法访问
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        //1. 首先检查请求头中是否有 token 访问令牌
        //  有: 将令牌交给 Realm 进行校验
        //  没有: 直接不允许访问, 因为设置了 login 和 register 不走这个过滤器
        if(isLoginAttempt(request, response)){
            try{
                this.executeLogin(request, response);
                return true;
            }catch (Exception e){
                ResponseErrorMag(response, e.getMessage());
                return false;
            }
        }
        ResponseErrorMag(response, "您如果想要执行此操作,请提供正确的凭证信息!");
        log.warn("用户尝试使用错误的凭证信息访问系统");
        return false;

    }

    /**
     * 重写 onAccessDenied 方法，避免父类中调用再次executeLogin
     * @param request ServletRequest
     * @param response ServletResponse
     * @return boolean
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {

//        log.warn("调用onAccessDenied拒绝访问");
        this.sendChallenge(request, response);
        return false;

    }

    /**
     * 对 token 访问令牌进行校验
     * @param request ServletRequest
     * @param response ServletResponse
     * @return boolean
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response){

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader(JwtConst.RESPONSE_HEADER);
        /*
         * 检查 token 字符串的格式和有效性
         */
        if(!jwtUtils.isJwtStr(authorization)){//不是 jwt 形式的字符串 或者
            log.warn("来自 JwtFilter 过滤器拦截 [不正确的凭证信息!]");
            throw new IncorrectCredentialsException("您使用错误的凭证尝试当前访问的资源!");
        }

        if(jwtUtils.isExpired(authorization) || jwtUtils.getClaimByToken(authorization) == null){//提交的 token 有误
            log.warn("来自 JwtFilter 过滤器拦截 [用户凭证过期!]");
            throw new ExpiredCredentialsException("您使用过期凭证尝试当前访问的资源, 请重新登录!");
        }

        JwtToken token = new JwtToken(authorization);
        // 提交给realm进行登入，如果错误他会抛出异常并捕获
        try{
            getSubject(request, response).login(token);
        }catch (Exception e){
            log.error("认证失败: " + e.getMessage());
            ResponseErrorMag(response, e.getMessage());
            return false;
        }
        // 如果没有抛出异常则代表认证成功，返回true
        return true;

    }

    /**
     * 对跨域提供支持
     * @param request ServletRequest
     * @param response ServletResponse
     * @return boolean
     * @throws Exception e
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); //标识允许哪个域到请求，直接修改成请求头的域
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");//标识允许的请求方法
        // 响应首部 Access-Control-Allow-Headers 用于 preflight request （预检请求）中，列出了将会在正式请求的 Access-Control-Expose-Headers 字段中出现的首部信息。修改为请求首部
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        //给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);

    }

    /**
     * 返回json格式对象
     * @param response ServletResponse
     * @param msg String
     */
    private void ResponseErrorMag(ServletResponse response, String msg) {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");

        try (PrintWriter out = httpServletResponse.getWriter()) {
            Result result = ResultUtils.resultWithoutData(ResultStatus.FAILED, msg);
            out.append(JSONUtil.toJsonStr(result));
//            log.error("报错: " + msg);
        } catch (IOException e) {
            log.error("返回Response信息出现IOException异常: {}", e.getMessage());
        }

    }
}
